package com.kingroad.auditproject.common.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @tags: http方法请求工具类
 * @author: ldr
 * @create: 2022-09-16 17:00:30
 **/
@Slf4j
public class HttpUtil {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public final static int CONNECT_TIMEOUT =60;
    public final static int READ_TIMEOUT=100;
    public final static int WRITE_TIMEOUT=60;
    private static OkHttpClient CLIENT;



    /**
     * 只有一个实例
     *
     * @return OkHttpClient
     */
    public static OkHttpClient getInstance() {

        if (CLIENT == null) {


//           // CLIENT = new OkHttpClient();
//            System.setProperty("javax.net.ssl.keyStore", "/Users/qingfeng/IdeaProjects/Mechatronics/Mechatronics-Boot/src/main/resources/static/jxgsgl.jks");
//            System.setProperty("javax.net.ssl.keyStorePassword", "123456");
//            System.setProperty("javax.net.ssl.keyStoreType", "JKS");
//            System.setProperty("javax.net.ssl.trustStore", "/Users/qingfeng/IdeaProjects/Mechatronics/Mechatronics-Boot/src/main/resources/static/jxgsgl.jks");
//            System.setProperty("javax.net.ssl.trustStorePassword", "123456");
//            System.setProperty("javax.net.ssl.trustType", "JKS");
            CLIENT=  new OkHttpClient.Builder()
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                    .writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS)//设置写的超时时间
                    .connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)//设置连接超时时间
                    //.sslSocketFactory(getSslFactory(path,pass),getMyX509TrustManager(path,pass))
                        .sslSocketFactory(createSSLSocketFactory(),new TrustAllManager())
                    .build();
        }
        return CLIENT;
    }

     public static  SSLSocketFactory getSslFactory()
    {
        SSLSocketFactory ssf=null;
        try {

try {
    SSLContext sslContext = null;
    sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            return true;
        }
    }).build();
    sslContext.init(null, null, new SecureRandom());
  ssf= sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
} catch (KeyManagementException e) {
    e.printStackTrace();
} catch (KeyStoreException e) {
    e.printStackTrace();
}
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return ssf;

    }



    /**
     * 将map中的参数拼接成url
     * @param params 参数map
     * @return eg: a=1&b=2&c=3
     */
    public static String getUrlFromMap(Map<String, Object> params) {
        StringBuffer tempParams = new StringBuffer();

        try {
            int pos = 0;
            for (String key : params.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }

                tempParams
                    .append(String.format("%s=%s", key, URLEncoder.encode((params.get(key)).toString(), "utf-8")));
                pos++;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return tempParams.toString();
    }

    /**
     * get() 返回字符串
     *
     * @param url get请求的url
     * @param params
     * @return String
     */
    public static String getForString(String url, Map<String, Object> params) {
        String rs = "";
        if (StringUtils.isEmpty(url)) {
            return "";
        }
        if (params != null && params.size()>0) {
            url = url + "?" + getUrlFromMap(params);
        }
        Request request = new Request.Builder().url(url).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        log.debug("get(): url = {}, rs = {}", url,rs);
        return rs;
    }

    public static String getForString(String url, Map<String, Object> params, Map<String, String> headers){
        String rs = "";

        if (StringUtils.isEmpty(url)) {
            return "";
        }

        if (params != null && params.size()>0) {
            url = url + "?" + getUrlFromMap(params);
        }
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (!CollectionUtils.isEmpty(headers)){
            headers.forEach(builder::addHeader);
        }
        Request request = builder.get().build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        log.debug("get(): url = {}, rs = {}", url,rs);
        return rs;
    }

    /**
     * post() 表单提交 返回字符串
     *
     * @param url
     * @param params
     * @return String
     */
    @SuppressWarnings("all")
    public static String postForString(String url, Map<String, Object> params) {
        String rs = "";

        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key).toString());
            }
        }
        RequestBody formBody = builder.build();

        Request request = new Request.Builder().url(url).post(formBody).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        log.info("postForString(): url = {}, params = {}, rs = {}", url, params, rs);
        return rs;
    }

    /**
     * delete() 表单提交 返回字符串
     *
     * @param url
     * @param params
     * @return String
     */
    @SuppressWarnings("all")
    public static String deleteForString(String url, Map<String, Object> params) {
        String rs = "";
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key).toString());
            }
        }
        RequestBody formBody = builder.build();

        Request request = new Request.Builder().url(url).delete(formBody).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        log.info("deleteForString(): url = {}, params = {}, rs = {}", url, params, rs);
        return rs;
    }
    public static String deleteForString(String url, Map<String, Object> params, Map<String, String> headers){
        String rs = "";
        if (StringUtils.isEmpty(url)) {
            return "";
        }
        if (params != null && params.size()>0) {
            url = url + "?" + getUrlFromMap(params);
        }
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (!CollectionUtils.isEmpty(headers)){
            headers.forEach(builder::addHeader);
        }
        Request request = builder.delete().build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        log.info("get(): url = {}, rs = {}", url,rs);
        return rs;
    }

    /**
     * put() 表单提交 返回字符串
     *
     * @param url
     * @param params
     * @return String
     */
    @SuppressWarnings("all")
    public static String putForString(String url, Map<String, Object> params) {
        String rs = "";
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key).toString());
            }
        }
        RequestBody formBody = builder.build();

        Request request = new Request.Builder().url(url).put(formBody).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        log.info("putForString(): url = {}, params = {}, rs = {}", url, params, rs);
        return rs;
    }

    public static String putForStringWithHeader(String url, Map<String,Object> params, Map<String,String> header) {
        String rs = "";
        FormBody.Builder builder = new FormBody.Builder();
        if (params != null && params.size()>0) {
            url = url + "?" + getUrlFromMap(params);
        }
        RequestBody formBody = builder.build();

        Request.Builder requestBuilder = new Request.Builder().url(url);
        for(String key: header.keySet()) {
            requestBuilder.addHeader(key,header.get(key));
        }
        Request request = requestBuilder.put(formBody).build();

        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("putForStringWithHeader(): url = {}, header = {}, params = {}, rs = {}",url, header,params,rs);
        return rs;
    }


    /**
     * 已经拼接好的url, 不需要再传参数map
     *
     * @param url
     * @return
     */
    public static JSONObject getForJSON(String url) {

        String resultStr = getForString(url, null);
        return JSONObject.parseObject(resultStr);
    }

    /**
     * get() 返回json对象
     *
     * @param url
     * @return JSONObject
     */
    public static JSONObject getForJSON(String url, Map<String, Object> params) {

        String resultStr = getForString(url, params);
        return JSONObject.parseObject(resultStr);
     //   return JSONObject.parseObject(resultStr);
    }

    /**
     * post() 返回json对象
     *
     * @param url
     * @param params
     * @return JSONObject
     */
    public static JSONObject postForJSON(String url, Map<String, Object> params) {
        String resultString = postForString(url, params);
        return JSONObject.parseObject(resultString);
    }

    /**
     * post() json格式 返回字符串
     *
     * @param url url
     * @param jsonString json字符串
     * @return String
     */
    @SuppressWarnings("all")
    public static String postJSONForString(String url, String jsonString) {
        final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        String rs = "";

        if (StringUtils.isEmpty(url)) {
            return "";
        }

        RequestBody requestBody = RequestBody.create(jsonType, jsonString);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs);
        return rs;
    }


    public static String postJSONForString(String url, String jsonString, Integer connSecond, Integer readSecond) throws Exception {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(connSecond, TimeUnit.SECONDS)
                .readTimeout(readSecond, TimeUnit.SECONDS)
                .build();
        final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        String rs = "";

        if (StringUtils.isEmpty(url)) {
            return "";
        }

        RequestBody requestBody = RequestBody.create(jsonType, jsonString);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = client.newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (Exception e) {
            throw new Exception(e);
        }
        log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs);
        return rs;
    }

    /**
     * post() json格式 返回字符串  带token请求头
     *
     * @param url url
     * @param jsonString json字符串
     * @return String
     */
    @SuppressWarnings("all")
    public static String postJSONForString(String url, String jsonString,String token) {
        final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        String rs = "";

        if (StringUtils.isEmpty(url)) {
            return "";
        }

        RequestBody requestBody = RequestBody.create(jsonType, jsonString);
        Request request = new Request.Builder().url(url).addHeader("token",token).post(requestBody).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs);
        return rs;
    }
    /**
     * post() json格式 返回字符串  带token请求头
     *
     * @param url url
     * @param jsonString json字符串
     * @return String
     */
    @SuppressWarnings("all")
    public static String postJSONForString(String url, String jsonString ,Map<String, String> headers) {
        final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        String rs = "";

        if (StringUtils.isEmpty(url)) {
            return "";
        }

        RequestBody requestBody = RequestBody.create(jsonType, jsonString);
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if(!CollectionUtils.isEmpty(headers)){
            headers.forEach((k,v)->builder.addHeader(k,v));
        }
        Request request = builder.post(requestBody).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs);
        return rs;
    }

    public static String postBytesForString(String url, byte[] bytes , Map<String, String> headers) {
        final MediaType jsonType = MediaType.parse("binary/octet-stream; charset=utf-8");
        String rs = "";

        if (StringUtils.isEmpty(url)) {
            return "";
        }

        RequestBody requestBody = RequestBody.create(jsonType, bytes);
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if(!CollectionUtils.isEmpty(headers)){
            headers.forEach((k,v)->builder.addHeader(k,v));
        }
        Request request = builder.post(requestBody).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, bytes, rs);
        return rs;
    }
    /**
     * put()  返回字符串
     *
     * @param url
     * @param params
     * @return String
     */
    @SuppressWarnings("all")
    public static String putJSONForString(String url,String jsonString, Map<String, String> headers) {
        final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        String rs = "";
        RequestBody requestBody = RequestBody.create(jsonType,jsonString);
        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if(!CollectionUtils.isEmpty(headers)){
            headers.forEach((k,v)->builder.addHeader(k,v));
        }
        builder.put(requestBody);
        Request request = builder.build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response  = call.execute();
            rs = response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("putJSONForString(): url = {}, params = {}, rs = {}, headers {}", url, jsonString, rs,headers);
        return rs;
    }

    @SuppressWarnings("all")
    public static Response getResponseForPost(String url, String jsonString, String[] authBase, boolean isAuth) {
        final MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
        if (StringUtils.isEmpty(url)) {
            return null;
        }

        RequestBody requestBody = RequestBody.create(jsonType, jsonString);
        Request request;
        if (isAuth){
            final String credential = Credentials.basic(authBase[0], authBase[1]);
            request = new Request.Builder().url(url).header("Authorization", credential).post(requestBody).build();
        }else{
            request = new Request.Builder().url(url).post(requestBody).build();
        }
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("postJSONForString(): url = {}, params = {}", url, jsonString);
        return response;
    }

    /**
     * post请求添加认证信息
     * @Param url：请求地址, params:参数，authBase：认证信息
     * @return String
     * @Date 14:03 2019/12/25
     * @Author zhl
     **/
    public static String postForAuthorization(String url, HashMap<String, Object> params, String[] authBase){
        final String credential = Credentials.basic(authBase[0], authBase[1]);
        String result = "";
        RequestBody fromBody = generateParametersForPost(params).build();
        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", credential)
                .post(fromBody)
                .build();
        Call call = CLIENT.newCall(request);
        try {
            Response response = call.execute();
            result = response.body().string();
        } catch (Exception e) {
            log.error("postForAuthorization-请求失败,url:{}, params:{}, authBase:{}",url, params, authBase, e);
        }
        log.info("postForAuthorization(): url = {}, authBase = {}, params = {}, rs = {}",url, authBase, params, result);
        return result;

    }

    public static String doHttpUrlencoded(String strUrl, Map<String, Object> params,String submitType) {
        String result = "";

        try {
            String requestBodyString = params.keySet().stream()
                    .map(x -> x + "=" + URLEncoder.encode(params.get(x).toString()))
                    .collect(Collectors.joining("&"));
            log.info("requestBodyString = {}",requestBodyString);
            URL url = new URL(strUrl);
            //通过调用url.openConnection()来获得一个新的URLConnection对象，并且将其结果强制转换为HttpURLConnection.
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod(submitType);
            //设置连接的超时值为30000毫秒，超时将抛出SocketTimeoutException异常
            urlConnection.setConnectTimeout(30000);
            //设置读取的超时值为30000毫秒，超时将抛出SocketTimeoutException异常
            urlConnection.setReadTimeout(30000);
            //将url连接用于输出，这样才能使用getOutputStream()。getOutputStream()返回的输出流用于传输数据
            urlConnection.setDoOutput(true);
            //设置通用请求属性为默认浏览器编码类型
            urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            //getOutputStream()返回的输出流，用于写入参数数据。
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(requestBodyString.getBytes());
            outputStream.flush();
            outputStream.close();
            //此时将调用接口方法。getInputStream()返回的输入流可以读取返回的数据。
            InputStream inputStream = urlConnection.getInputStream();
            byte[] data = new byte[1024];
            StringBuilder sb = new StringBuilder();
            //inputStream每次就会将读取1024个byte到data中，当inputSteam中没有数据时，inputStream.read(data)值为-1
            while (inputStream.read(data) != -1) {
                String s = new String(data, Charset.forName("utf-8"));
                sb.append(s);
            }
            result = sb.toString();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("postForUrlencoded(): url = {}, params = {}, rs = {}", strUrl, params, result);
        return result;
    }

    @SuppressWarnings("all")
    public static String postUrlEncodeForm(String url,Map<String,Object> map) {
        String result = "";

        //处理请求参数
        List<NameValuePair> valuePairs = new LinkedList<>();
        map.forEach((key, value) -> valuePairs.add(new BasicNameValuePair(key, value.toString())));
/*        for(Map.Entry<String,Object> entry : map.entrySet()) {
            NameValuePair valuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
            valuePairs.add(valuePair);
        }*/
        try {
        //设置client参数
            HttpClient client = HttpClientBuilder.create().build();

        //发送请求
            HttpPost post = new HttpPost(url);
            HttpEntity entity = new UrlEncodedFormEntity(valuePairs,"UTF-8");
            post.setEntity(entity);
            HttpResponse response = client.execute(post);

            //处理响应结果
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new RuntimeException("statusCode = [" + statusCode + "]");
            } else {
                HttpEntity respEntity = response.getEntity();
                result = EntityUtils.toString(respEntity,"UTF-8");
                }
            } catch (IOException e) {
                e.getMessage();
        }
        log.info("postForUrlencoded(): url = {}, params = {}, rs = {}", url, map, result);
        return result;
    }

    @SuppressWarnings("all")
    public static String putUrlEncodeForm(String url,Map<String,Object> map) {
        String result = "";

        //处理请求参数
        List<NameValuePair> valuePairs = new LinkedList<>();
        map.forEach((key, value) -> valuePairs.add(new BasicNameValuePair(key, value.toString())));
        try {
            //设置client参数
            HttpClient client = HttpClientBuilder.create().build();

            //发送请求
            HttpPut put = new HttpPut(url);
            HttpEntity entity = new UrlEncodedFormEntity(valuePairs,"UTF-8");
            put.setEntity(entity);
            HttpResponse response = client.execute(put);

            //处理响应结果
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new RuntimeException("statusCode = [" + statusCode + "]");
            } else {
                HttpEntity respEntity = response.getEntity();
                result = EntityUtils.toString(respEntity,"UTF-8");
            }
        } catch (IOException e) {
            e.getMessage();
        }
        log.info("putUrlEncodeForm(): url = {}, params = {}, rs = {}", url, map, result);
        return result;
    }


    public static String postXmlForString(String url, String xmlString) {
        final MediaType xmlType = MediaType.parse("text/xml; charset=utf-8");
        String rs = "";

        if (StringUtils.isEmpty(url)) {
            return "";
        }

        RequestBody requestBody = RequestBody.create(xmlType, xmlString);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, xmlString, rs);
        return rs;
    }

    /**
     * post() json格式
     *
     * @param url url
     * @param jsonString json格式字符串
     * @return JSONObject
     */
    public static JSONObject postJSONForJSON(String url, String jsonString) {
        String resultString = postJSONForString(url, jsonString);
        return JSONObject.parseObject(resultString);
    }


    /**
     * post() json格式 返回字符串
     *
     * @param url url
     * @param jsonString json字符串
     * @return String
     */
    public static String postJSONForStringGBK(String url, String jsonString) {
        final MediaType jsonType = MediaType.parse("application/json; charset=gb2312");
        String rs = "";

        if (StringUtils.isEmpty(url)) {
            return "";
        }

        RequestBody requestBody = RequestBody.create(jsonType, jsonString);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs);
        return rs;
    }

    /**
     * post() json格式
     *
     * @param url url
     * @param jsonString json格式字符串
     * @return JSONObject
     */
    public static JSONObject postJSONForJSONGBK(String url, String jsonString) {
        String resultString = postJSONForStringGBK(url, jsonString);
        return JSONObject.parseObject(resultString);
    }

    /**
     * 获取post json过来的数据
     *
     * @param request httpServletRequest对象
     * @return 字符串
     */
    public static String receivePost(HttpServletRequest request) {
        String res = "";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            res = URLDecoder.decode(sb.toString(), "utf-8");
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    public static String receivePostForGbk(HttpServletRequest request){
        String res = "";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            res = URLDecoder.decode(sb.toString(), "GBK");
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    /**
     * Post() 提交带header
     * @param url
     * @param header
     * @param params
     * @return
     */
    public static String postForStringWithHeader(String url, Map<String,String> header, Map<String,String> params) {
        String rs = "";

        FormBody.Builder builder = new FormBody.Builder();

        if (params != null && !params.isEmpty()) {
            for(String key : params.keySet()) {
                builder.add(key,params.get(key));
            }
        }

        RequestBody formBody = builder.build();

        Request.Builder requestBuilder = new Request.Builder().url(url);//.post(formBody).build();

        for(String key: header.keySet()) {
            requestBuilder.addHeader(key,header.get(key));
        }

        Request request = requestBuilder.post(formBody).build();

        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("post(): url = {}, header = {}, params = {}, rs = {}",url, header,params,rs);
        return rs;
    }

    /**
     * post() 提交带header 返回JSON
     * @param url
     * @param params
     * @return
     */
    public static JSONObject postForJSONWithHeader(String url, Map<String,String> header, Map<String,String> params) {
        String resultString = postForStringWithHeader(url,header,params);
        return JSONObject.parseObject(resultString);
    }


    public static String receivePostGBK(HttpServletRequest request) {
        String res = "";
        String resgbk = "";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            log.info("***********to UTF-16BE:{}" ,sb.toString().getBytes());

            String byte_s="";
            for(byte i:sb.toString().getBytes())
            {
                byte_s=byte_s+i;
            }

            log.info("***********to sb:{}" ,new String(sb));
            log.info("***********to sb.toString:{}" ,sb.toString());
            log.info("***********to byte_s:{}", byte_s);
            log.info("***********to GBK:{}" ,new String(sb.toString().getBytes(),"GBK"));
            log.info("***********to GB2312:{}" ,new String(sb.toString().getBytes(),"GB2312"));
            log.info("***********to UTF:{}" ,new String(sb.toString().getBytes(),"UTF-8"));
            log.info("***********to UTF-16BE:{}" ,new String(sb.toString().getBytes(),"UTF-16BE"));





            res = URLDecoder.decode(sb.toString(), "GB2312");
            resgbk = URLDecoder.decode(sb.toString(), "GBK");
            log.info("receivePostGBK : URLDecoder res = {}, resgbk = {}, rs = {}", res, resgbk);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    private static FormBody.Builder generateParametersForPost(HashMap<String, Object> parameters) {

        FormBody.Builder builder = new FormBody.Builder();

        if(parameters.size()>0){
            Object[] keys = parameters.keySet().toArray();

            for(Object key : keys){
                Object ff = parameters.get(key);
                String aa = parameters.get(key).toString();

                builder.add(key.toString(),parameters.get(key).toString());
            }
        }
        return builder;
    }


    public static String receivePostEncoding(HttpServletRequest request, String CharacterEncoding) {
        String res = "";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            log.info("***********to CharacterEncoding:{}" ,new String(sb.toString().getBytes(),CharacterEncoding));

            res = URLDecoder.decode(sb.toString(), CharacterEncoding);
            log.info("receivePostEncoding : URLDecoder res = {}", res);

        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return res;
    }

    public static String getRequestBody(HttpServletRequest request)
            throws IOException {
        StringBuilder httpBody = new StringBuilder();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null) {
                httpBody.append(line);
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return httpBody.toString();
    }

    /**
     * 同步post json数据 <有头信息>
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String post(String url, String json,Map<String, String> headers) {
        String rs = "";
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().headers(Headers.of(headers)).url(url).post(body).build();
        Call call = HttpUtil.getInstance().newCall(request);
        Response response = null;
        try {
            response = call.execute();
            rs = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     * @param strURL url地址
     * @return url请求参数部分
     * @author lzf
     */
    private static String TruncateUrlPage(String strURL){
        String strAllParam=null;
        String[] arrSplit=null;
        strURL=strURL.trim().toLowerCase();
        arrSplit=strURL.split("[?]");
        if(strURL.length()>1){
            if(arrSplit.length>1){
                for (int i=1;i<arrSplit.length;i++){
                    strAllParam = arrSplit[i];
                }
            }
        }
        return strAllParam;
    }

    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     * @param URL  url地址
     * @return  url请求参数部分
     */
    public static Map<String, String> urlSplit(String URL){
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit=null;
        String strUrlParam=TruncateUrlPage(URL);
        if(strUrlParam==null){
            return mapRequest;
        }
        arrSplit=strUrlParam.split("[&]");
        for(String strSplit:arrSplit){
            String[] arrSplitEqual=null;
            arrSplitEqual= strSplit.split("[=]");
            //解析出键值
            if(arrSplitEqual.length>1){
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            }else{
                if(arrSplitEqual[0]!=""){
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

private static SSLSocketFactory createSSLSocketFactory() {

    SSLSocketFactory sSLSocketFactory = null;

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[]{new TrustAllManager()},
                new SecureRandom());
        sSLSocketFactory = sc.getSocketFactory();
    } catch (Exception e) {
    }

    return sSLSocketFactory;
}

private static class TrustAllManager implements X509TrustManager {
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)

            throws CertificateException {
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return  new X509Certificate[0];
    }
}

private static class TrustAllHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}


}
